package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.FileUploadVO;
import com.cskaoyan.bean.Storage;
import com.cskaoyan.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
 * @author WeitenHong
 * @date 2020/10/1 19:17
 */

@RestController
public class FileUploadController {

    @Autowired
    AdminService adminService;

    @RequestMapping("admin/storage/create")
    public BaseRespVo fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        int length = file.getBytes().length;
        String uuid = UUID.randomUUID().toString();
        String filename=uuid+"-"+originalFilename;
        int i = filename.hashCode();
        String hexString = Integer.toHexString(i);
        filename=hexString;
        Storage storage = new Storage();
        storage.setName(originalFilename);
        storage.setSize(length);
        storage.setType(contentType);
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());
        storage.setKey(filename);
        storage.setId(i);
        storage.setUrl("http://localhost:8083/"+filename+"."+contentType.substring(6));
        //File destFile = new File("F://git//images", filename+"."+contentType.substring(6));
        File destFile = new File("F:/git/images/", filename+"."+contentType.substring(6));
        file.transferTo(destFile);
        int code = adminService.addStorage(storage);
        if(code != 1){
            return BaseRespVo.fail("本地存储失败");
        }
        return BaseRespVo.ok(storage);
    }
}
